﻿using Client.ICommandNotify;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Client.ViewModel.Revolve
{
    public class RevolveViewModel:NotifyBase
    {
        public RevolveViewModel()
        {
            Selectcommand = new Command(ReverseDoExecute, ReverseCanExecute);
        }


        #region 命令
        public Command Selectcommand { get; set; }
        #endregion
        #region 方法
        private bool ReverseCanExecute()
        {
            return string.IsNullOrWhiteSpace(DocumentNumber) ? false : true;
        }

        private async void ReverseDoExecute(object obj)
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            var Http_ = HelpTools.IOC.Getobject<Client.HttpHelp.Http>();
             Http_.Uir = "http://cpms_revolve.scrbg.com/json.rpc";
            string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
            if (string.IsNullOrWhiteSpace(strconfig))
            {
                Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                return;
            }
            DbContext_.SqlConfigstr = strconfig;
            if(obj as string == "1")
            {
                Dialog_.OpenDialog = true;
                ResponseData = await Task.Run(async () =>
                {
                    var data = DbContext_.Where($"SELECT * FROM [dbo].[Settle_Zcjs] WHERE BillNo='{DocumentNumber}'").Select().Select(o => new
                    {
                        BillId = o["BillId"].ToString(),
                        WorkId = o["WorkId"].ToString(),
                    }).FirstOrDefault();
                    if (data != null)
                    {
                        int index = DbContext_.Update($"UPDATE Settle_ZcjsDtl SET FtYsTaxAmount=FtTaxAmount WHERE BillId='{data.BillId}'");
                        if (index > 0)
                        {
                            string strconfig1 = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == "基础")?.FirstOrDefault()?.ConnectingString;
                            if (string.IsNullOrWhiteSpace(strconfig1))
                                return "数据连接字符串为空,请检查数据库配置是否正确";
                            DbContext_.SqlConfigstr = strconfig1;
                            DbContext_.Update($"DELETE KDPM_Record WHERE PMID='{data.BillId}'");
                            Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
                            parameterModel.method = "SettleRevolve.Zcjs.SendToKD";
                            parameterModel.@params = new
                            {
                                BillId = data.BillId,
                                IsCallbackEasShareAudit = true
                            };
                            return await Http_.PostData(parameterModel, "", "application/json");
                        }
                    }
                    return "单据数据没找到";
                }
                    );
                Dialog_.OpenDialog = false;
            }
            if(obj as string == "2")
            {
                Dialog_.OpenDialog = true;
                await Task.Run(() =>
                {
                    var zcjsdtl = DbContext_.Where($"SELECT b.SourceDtlId,b.FtTaxAmount FROM Settle_Zcjs a JOIN Settle_ZcjsDtl b on a.BillId=b.BillId WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                    {
                        return new
                        {
                            SourceDtlId = o["SourceDtlId"].ToString(),
                            FtTaxAmount = decimal.Parse(string.IsNullOrWhiteSpace(o["FtTaxAmount"].ToString()) ? "0" : o["FtTaxAmount"].ToString())
                        };
                    });
                    if (zcjsdtl != null && zcjsdtl.Any() && zcjsdtl.Count() == 1)
                    {
                        var Stuff_CheckTax = DbContext_.Where($"SELECT a.TaxAmount FROM Stuff_CheckDtl b JOIN Stuff_Check a ON a.BillId=b.BillId WHERE DtlId = '{zcjsdtl.FirstOrDefault().SourceDtlId}'").Select().Select(o =>
                        {
                            return new
                            {
                                TaxAmount = o["TaxAmount"].ToString()
                            };
                        });
                        if (Stuff_CheckTax != null && Stuff_CheckTax.Any())
                        {
                            int indx = DbContext_.Update($"UPDATE [dbo].[Stuff_CheckDtl] SET [FtTaxAmount] = {Stuff_CheckTax.FirstOrDefault().TaxAmount} WHERE CONVERT(NVARCHAR(MAX), [DtlId]) = N'{zcjsdtl.FirstOrDefault().SourceDtlId}'");
                            if (indx > 0)
                            {
                                App.Current.Dispatcher.BeginInvoke(new Action(() => {
                                    Dialog_.OpenDialog = false;
                                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                                }));
                               
                            } 
                            else
                            {
                                App.Current.Dispatcher.BeginInvoke(new Action(() => {
                                    Dialog_.OpenDialog = false;
                                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                                }));
                              
                            }   
                        }
                        return;
                    }
                    else
                    {
                        if (zcjsdtl != null && zcjsdtl.Any() && zcjsdtl.Count() > 1)
                        {
                            foreach (var item in zcjsdtl)//数据量小一个一个更新
                            {
                                DbContext_.Update($"UPDATE [dbo].[Stuff_CheckDtl] SET [FtTaxAmount] = {item.FtTaxAmount} WHERE CONVERT(NVARCHAR(MAX), [DtlId]) = N'{item.SourceDtlId}'");
                            }
                        }
                        App.Current.Dispatcher.BeginInvoke(new Action(() => {
                            Dialog_.OpenDialog = false;
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                        }));                    
                        return;
                    }
                });
               
            }
        }
        #endregion
        #region 属性
        private string Title_ = "周材";
        //标题
        public string Title
        {
            get { return Title_; }
            set { Title_ = value; }
        }

        private string DocumentNumber_;
        //单据编号
        public string DocumentNumber
        {
            get { return DocumentNumber_; }
            set { DocumentNumber_ = value; }
        }
        private string ResponseData_;
        //HTTP请求响应数据
        public string ResponseData
        {
            get { return ResponseData_; }
            set { ResponseData_ = value;
                SetProperty(ref DocumentNumber_, DocumentNumber);
            }
        }

        #endregion
    }
}
